package com.jprocms.module.cms.config;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.ObjectUtil;
import lombok.Data;

import java.net.URL;

import static com.jprocms.module.cms.constant.CmsSysConstants.SPT;

/**
 * @author jprocms
 */
@Data
public class TplFtpConfigProperties {

    private String ip;

    private Integer port;

    private String username;

    private String password;

    /**
     * 访问编码
     */
    private String encoding;

    private String url;

    /**
     * 获取拼装之后的访问路径 (不包含ip:port)
     *
     * @param siteId
     * @param relativePath
     * @return
     */
    public String getRealPath(String sitePath, String relativePath, String separator) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(separator);
        stringBuffer.append(sitePath);
        if (ObjectUtil.isNotEmpty(relativePath)) {
            if (!relativePath.startsWith(separator)) {
                stringBuffer.append(separator);
            }
            stringBuffer.append(relativePath);
        }
        return stringBuffer.toString();
    }

    public String getPath(String sitePath, String relativePath) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(sitePath);
        if (ObjectUtil.isNotEmpty(relativePath)) {
            if (!relativePath.startsWith(SPT)) {
                stringBuffer.append(SPT);
            }
            stringBuffer.append(relativePath);
        }
        return stringBuffer.toString().replace("\\", SPT);
    }

    public URL getUrl(String relativePath) {
        if (relativePath == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder(url);
        if (!url.endsWith(SPT) && !relativePath.startsWith(SPT)) {
            sb.append(SPT);
        }
        //截取掉 模板路径的.html
        int index = relativePath.lastIndexOf(".");
        if (index > -1) {
            relativePath = relativePath.substring(0, index);
        }
        sb.append(relativePath);
        return UrlBuilder.ofHttp(sb.toString()).toURL();
    }

    public String getPrefixPath(String sitePath, String solution) {
        StringBuilder stringBuffer = new StringBuilder(url);
        if (!url.endsWith(SPT)) {
            stringBuffer.append(SPT);
        }
        stringBuffer.append(sitePath);
        stringBuffer.append(SPT);
        stringBuffer.append(solution);
        stringBuffer.append(SPT);
        return stringBuffer.toString();
    }
}
